import 'dart:convert';
import 'package:find_friend/common/common_widget.dart';
import 'package:find_friend/common/event_bus.dart';
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/login&register/model/shared_user_info.dart';
import 'package:find_friend/pages/search/search_res.dart';
import 'package:find_friend/pages/xspace/detail/xdetailpage.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../model/school_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'view/xallscholl_cell.dart';

const String _record_location_key = "record_location_key";

class XAllSchoolPage extends StatefulWidget {

  final int schooltype;
  final bool follow; // 是否是关注人的帖子
  _XAllSchoolPageState _state;

  XAllSchoolPage({Key key, this.schooltype = 0, this.follow = false}) : super(key: key);

  refreshData({dynamic data, hot = true}) {
    _state._reloadData(data: data, hot: hot);
  }

  goTop() {
    _state._goTop();
  }

  @override
  _XAllSchoolPageState createState() => _state = _XAllSchoolPageState();
}

class _XAllSchoolPageState extends State<XAllSchoolPage> {

  RefreshController _refreshController = RefreshController(initialRefresh: true);
  List<ArticleModel> list = [];
  ScrollController _scrollController = ScrollController();
  int page = 0;
  bool orderbyhot = true;
  int lastpage;
  String mineMobile;
  @override
  void initState() {
    super.initState();

    if(widget.follow != true) {
      EventMineBus.instance.addListener(EventMineKeys.RecordLastLocation, (arg) async { 
        SharedPreferences share = await SharedPreferences.getInstance();
        Map<String, dynamic> record = {
          "schooltype": widget.schooltype ?? 0,
          "page": page,
        };
        share.setString(_record_location_key + widget.schooltype.toString(), json.encode(record));
      });
      _getLastLocation();
    }
    
    SharedUserInfo.instance().then((value) {
      mineMobile = value.mobile;
      if(mounted) setState(() { });
    });
  }

  @override
  void dispose() {
    _refreshController.dispose();
    _scrollController.dispose();
    EventMineBus.instance.removeListener(EventMineKeys.RecordLastLocation);
    super.dispose();
  }

  // 获取上次记录的位置
  _getLastLocation() async {
    SharedPreferences share = await SharedPreferences.getInstance();
    String str = share.getString(_record_location_key + widget.schooltype.toString());
    if(str != null) {
      Map<String, dynamic> res = json.decode(str);
      if(list.length >= 4) {
        setState(() {
          list.insert(3, null);
        });
      }

      lastpage = res["page"];
    }
  }

  // 回到上次浏览位置
  _jumpLastLocation() async {
    SharedPreferences share = await SharedPreferences.getInstance();
    share.remove(_record_location_key + widget.schooltype.toString());
    page = lastpage - 1;
    lastpage = null;
    setState(() {
      list.removeAt(3);
    });
    _refreshController.requestLoading();
  }
  

  _reloadData({dynamic data, bool hot}) {
    if(data == null) {
      orderbyhot = hot;
      _refreshController.requestRefresh();
    } else {
      ArticleModel model = ArticleModel.fromJson(data);
      setState(() {
        list.insert(0, model);
      });
    }
  }

  _goTop() {
    // curve 必填，不填不起作用
    _scrollController.animateTo(0, duration: Duration(milliseconds: 100), curve: Curves.easeIn);
  }

  _onRefresh() {
    page = 1;
    _request(isrefresh: true);
  }

  _onLoading() {
    page += 1;
    _request();
  }

  _endrefres() {
    if(_refreshController.isRefresh) _refreshController.refreshCompleted();
    if(_refreshController.isLoading) _refreshController.loadComplete();
  }

  _endNormoreData(int perpage) {
    if(perpage < 5) {
      _refreshController.loadNoData();
    } else {
      _refreshController.loadComplete();
    }
  }

  _request({bool isrefresh = false}) {
    var params = {"rows":5, "page":page, "my_school":widget.schooltype,"upvote_order": orderbyhot};
    if(widget.follow == true){
      params["in_follow"] = widget.follow;
    }
    Networktool.request(API.article, params: params, method: NETWORKHTTPMethod.GET, success: (data){
      if(data != null) {
        ArticleResponModel model = ArticleResponModel.fromJson(data);
        _endNormoreData(model.data.data?.length ?? 0);
        if(isrefresh) list.clear();
        list.addAll(model.data?.data ?? []);
        if(mounted) setState(() {});
      }
    }
    ,finaly: _endrefres
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: APP_scaffold_back_color,
      body: SafeArea(
        child: Stack(
          children: [
            CustomRefreshWidget(
              onRefresh: _onRefresh,
              onLoading: _onLoading,
              controller: _refreshController,
              page: page,
              child: ListView.builder(
                itemCount: list.length,
                controller: _scrollController,
                itemBuilder: (context, index){
                  if(index == 3 && lastpage != null) {
                    return XAllReturnWidget(onRebackLastLocation: _jumpLastLocation,);
                  } else{
                    return GestureDetector(
                      onTap: (){
                        // Navigator.of(context).pushNamed("/xdetailpage", arguments: list[index]);
                        push(context, XDetailPage(model: list[index], onRefreshData: _onRefresh));
                      },
                      child: XallSchoolCell(model: list[index], isself: mineMobile == list[index].mobile,onRefreshData: (){
                        _refreshController.requestRefresh();
                      },)
                    );
                  }
                }
              ),
            ),
            Positioned.fill(
              child: Offstage(
                offstage: list.length != 0,
                child: NodataWidget(text: "居然什么都没有!",)
              )
            )
          ],
        ),
      ),
    );
  }
}







class XAllReturnWidget extends StatelessWidget {

  final Function onRebackLastLocation;

  const XAllReturnWidget({Key key, this.onRebackLastLocation}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: onRebackLastLocation,
      child: Container(
        margin: const EdgeInsets.only(left: 75, right: 75, top: 10),
        padding: const EdgeInsets.symmetric(vertical: 10),
        alignment: Alignment.center,
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border.all(color:APP_divider_color, width: 0.5),
          borderRadius: BorderRadius.circular(20)
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("回到上次浏览位置",style: instanceTextStyle(11, APP_font_black),),
            SizedBox(width: 5,),
            Image.asset("assets/huidao.png")
          ],
        ),
      ),
    );
  }
}

